<?php

class Tv_IndexController extends Core_Controller_Action_Standard {

    public function browseAction() {
        if (!$this->_helper->requireAuth()->setAuthParams('tv', null, 'view')->isValid())
            return;

        $values = array();
        $values = $this->_getAllParams();

        $this->view->paginator = $paginator = Engine_Api::_()->getItemTable('tv')->getTvPaginator($values);
        $items_count = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('tv.page', 10);
        $paginator->setItemCountPerPage($items_count);
        $paginator->setCurrentPageNumber($this->_getParam('page', 1));

        // Render
        $this->_helper->content
                //->setNoRender()
                ->setEnabled()
        ;
    }

    public function createAction() {
        if (!$this->_helper->requireAuth()->setAuthParams('tv', null, 'create')->isValid())
            return;

        // Get navigation
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('tv_main', array(), 'tv_main_create');

        // Get form
        $this->view->form = $form = new Tv_Form_Create();

        if (!$this->getRequest()->isPost()) {
            return;
        }

        if (!$form->isValid($this->getRequest()->getPost())) {
            $values = $form->getValues('url');
            //$form->set = $values['url'];
            // set title and description using getinfromation() here?
            return;
        }

        $viewer = Engine_Api::_()->user()->getViewer();
        $values = $form->getValues();
        $values['owner_id'] = $viewer->getIdentity();
        $values['owner_type'] = 'user';
        $insert_action = false;

        $table = Engine_Api::_()->getDbtable('tvs', 'tv');

        $db = $table->getAdapter();
        $db->beginTransaction();

        try {
            $tv = $table->createRow();

            $tv->setFromArray($values);
            $tv->save();
            
            if (!empty($values['photo'])) {
                $tv->setPhoto($form->photo);
            }
            
            if($tv->type == 4){
                $tv->status = 1;
                $tv->save();
            }
            
            $thumbnail = $this->handleThumbnail($tv->type, $tv->code);
            $ext = ltrim(strrchr($thumbnail, '.'), '.');
            $thumbnail_parsed = @parse_url($thumbnail);

            if (@GetImageSize($thumbnail)) {
                $valid_thumb = true;
            } else {
                $valid_thumb = false;
            }

            if ($valid_thumb && $thumbnail && $ext && $thumbnail_parsed && in_array($ext, array('jpg', 'jpeg', 'gif', 'png'))) {
                $tmp_file = APPLICATION_PATH . '/temporary/link_' . md5($thumbnail) . '.' . $ext;
                $thumb_file = APPLICATION_PATH . '/temporary/link_thumb_' . md5($thumbnail) . '.' . $ext;

                $src_fh = fopen($thumbnail, 'r');
                $tmp_fh = fopen($tmp_file, 'w');
                stream_copy_to_stream($src_fh, $tmp_fh, 1024 * 1024 * 2);

                $image = Engine_Image::factory();
                $image->open($tmp_file)
                        ->resize(120, 240)
                        ->write($thumb_file)
                        ->destroy();

                try {
                    $thumbFileRow = Engine_Api::_()->storage()->create($thumb_file, array(
                        'parent_type' => $tv->getType(),
                        'parent_id' => $tv->getIdentity()
                            ));

                    // Remove temp file
                    @unlink($thumb_file);
                    @unlink($tmp_file);
                } catch (Exception $e) {
                    
                }
                $information = $this->handleInformation($tv->type, $tv->code);

                $tv->duration = $information['duration'];
                if (!$tv->description) {
                    $tv->description = $information['description'];
                }
                $tv->photo_id = $thumbFileRow->file_id;
                $tv->status = 1;
                $tv->save();

                // Insert new action item
                $insert_action = true;
            }

            if ($values['ignore'] == true) {
                $tv->status = 1;
                $tv->save();
                $insert_action = true;
            }

            // CREATE AUTH STUFF HERE
             // CREATE AUTH STUFF HERE
           $auth = Engine_Api::_()->authorization()->context;
            $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');

            if (empty($values['auth_view'])) {
                $values['auth_view'] = 'everyone';
            }

            if (empty($values['auth_comment'])) {
                $values['auth_comment'] = 'everyone';
            }
            
            if (empty($values['favourite'])) {
                $values['favourite'] = 'everyone';
            }
            if (empty($values['invate'])) {
                $values['invate'] = 'everyone';
            }
         
            
            
            $viewMax = array_search($values['auth_view'], $roles);
            $commentMax = array_search($values['auth_comment'], $roles);
            $favouriteMax = array_search($values['favourite'], $roles);
            $inviteMax = array_search($values['invate'], $roles);
          
            
            
            foreach ($roles as $i => $role) {
                $auth->setAllowed($tv, $role, 'view', ($i <= $viewMax));
                $auth->setAllowed($tv, $role, 'comment', ($i <= $commentMax));
                $auth->setAllowed($tv, $role, 'favourite', ($i <= $favouriteMax));
                $auth->setAllowed($tv, $role, 'invite', ($i <= $inviteMax));
              
            }

            $activityApi = Engine_Api::_()->getDbtable('actions', 'activity');

            $action = $activityApi->addActivity($viewer, $tv, 'tv_create');

            if ($action) {
                $activityApi->attachActivity($action, $tv);
            }

            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }

        return $this->_forward('success', 'utility', 'core', array(
                    'messages' => array(Zend_Registry::get('Zend_Translate')->_('TV was created successfully')),
                    'redirect' => $this->_helper->redirector->gotoRoute(array('tv_id' => $tv->getIdentity()), 'tv_specific', true),
                ));
    }

    public function validationAction() {
        $video_type = $this->_getParam('type');
        $code = $this->_getParam('code');
        $ajax = $this->_getParam('ajax', false);
        $valid = false;

        // check which API should be used
        if ($video_type == "youtube") {
            $valid = $this->checkYouTube($code);
        }
        if ($video_type == "vimeo") {
            $valid = $this->checkVimeo($code);
        }

        $this->view->code = $code;
        $this->view->ajax = $ajax;
        $this->view->valid = $valid;
    }

    // YouTube Functions
    public function checkYouTube($code) {
        if (!$data = @file_get_contents("http://gdata.youtube.com/feeds/api/videos/" . $code))
            return false;
        if ($data == "Video not found")
            return false;
        return true;
    }

    // Vimeo Functions
    public function checkVimeo($code) {
        //http://www.vimeo.com/api/docs/simple-api
        //http://vimeo.com/api/v2/video
        $data = @simplexml_load_file("http://vimeo.com/api/v2/video/" . $code . ".xml");
        $id = count($data->video->id);
        if ($id == 0)
            return false;
        return true;
    }

    // handles thumbnails
    public function handleThumbnail($type, $code = null) {
        switch ($type) {
            //youtube
            case "1":
                //http://img.youtube.com/vi/Y75eFjjgAEc/default.jpg
                return "http://img.youtube.com/vi/$code/default.jpg";
            //vimeo
            case "2":
                //thumbnail_medium
                $data = simplexml_load_file("http://vimeo.com/api/v2/video/" . $code . ".xml");
                $thumbnail = $data->video->thumbnail_medium;
                return $thumbnail;
        }
    }

    // retrieves infromation and returns title + desc
    public function handleInformation($type, $code) {
        switch ($type) {
            //youtube
            case "1":
                $yt = new Zend_Gdata_YouTube();
                $youtube_video = $yt->getVideoEntry($code);
                $information = array();
                $information['title'] = $youtube_video->getTitle();
                $information['description'] = $youtube_video->getVideoDescription();
                $information['duration'] = $youtube_video->getVideoDuration();
                //http://img.youtube.com/vi/Y75eFjjgAEc/default.jpg
                return $information;
            //vimeo
            case "2":
                //thumbnail_medium
                $data = simplexml_load_file("http://vimeo.com/api/v2/video/" . $code . ".xml");
                $thumbnail = $data->video->thumbnail_medium;
                $information = array();
                $information['title'] = $data->video->title;
                $information['description'] = $data->video->description;
                $information['duration'] = $data->video->duration;
                //http://img.youtube.com/vi/Y75eFjjgAEc/default.jpg
                return $information;
        }
    }

    public function favouriteAction() {
        if (!$this->_helper->requireAuth()->setAuthParams('tv', null, 'view')->isValid())
            return;
        // Get navigation
//        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
//                ->getNavigation('tv_main', array(), 'tv_main_favourite');
        
        $viewer = Engine_Api::_()->user()->getViewer();

        $values = array();
        $values = $this->_getAllParams();
        $values['user_id'] = $viewer->getIdentity();

        $this->view->paginator = $paginator = Engine_Api::_()->getItemTable('tv')->getTvPaginator($values);
        $items_count = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('tv.page', 10);
        $paginator->setItemCountPerPage($items_count);
        $paginator->setCurrentPageNumber($this->_getParam('page', 1));

        // Render
        $this->_helper->content
                //->setNoRender()
                ->setEnabled()
        ;
    }

}
